package com.excel.tools;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.ss.usermodel.Cell;

public class CellFormatter {

	public static String getStringCellValue(Cell cell) { // 获取单元格数据内容为字符串类型的数据
		if (cell == null) {
			return "";
		}
		String strCell = "";
		switch (cell.getCellType()) {
		case HSSFCell.CELL_TYPE_STRING:
			strCell = cell.getStringCellValue();
			break;
		case HSSFCell.CELL_TYPE_NUMERIC:
			strCell = String.valueOf(cell.getNumericCellValue());
			break;
		case HSSFCell.CELL_TYPE_BOOLEAN:
			strCell = String.valueOf(cell.getBooleanCellValue());
			break;
		case HSSFCell.CELL_TYPE_BLANK:
			strCell = "";
			break;
		default:
			strCell = "";
			break;
		}
		if (strCell == null || strCell.equals("")) {
			return "";
		}
		return strCell;
	}

	public static Date getDateCellValue(Cell cell, String datePattern) throws ParseException { // 获取单元格数据内容为日期类型的数据
		if (cell == null) {
			return null;
		}
		Date date = null;
		switch (cell.getCellType()) {
		case HSSFCell.CELL_TYPE_NUMERIC:
			date = cell.getDateCellValue();
			break;
		case HSSFCell.CELL_TYPE_STRING:
			String dateStr = cell.getStringCellValue();
			date = new SimpleDateFormat(datePattern).parse(dateStr);
			break;
		default: 
			date = null;
			break;
		}
		return date;
	}
	
	public static boolean getBooleanCellValue(Cell cell){ // 获取单元格数据内容为逻辑类型的数据
		if (cell == null) {
			return false;
		}
		boolean b = false;
		switch (cell.getCellType()) {
		case HSSFCell.CELL_TYPE_NUMERIC:
			double numeric = cell.getNumericCellValue();
			b = (int)numeric == 1 ? true : false;
			break;
		case HSSFCell.CELL_TYPE_STRING:
			String booleanStr = cell.getStringCellValue();
			b = new Boolean(booleanStr);
			break;
		case HSSFCell.CELL_TYPE_BOOLEAN:
			b = cell.getBooleanCellValue();
			break;
		default: 
			b = false;
			break;
		}
		return b;
	}
	
	public static double getNumericCellValue(Cell cell) { // 获取单元格数据内容为数值类型的数据
		if (cell == null) {
			return 0.0;
		}
		double numeric = 0.0;
		switch (cell.getCellType()) {
		case HSSFCell.CELL_TYPE_NUMERIC:
			numeric = cell.getNumericCellValue();
			break;
		case HSSFCell.CELL_TYPE_STRING:
			String numericStr = cell.getStringCellValue();
			numeric = Double.valueOf(numericStr);
			break;
		default: 
			numeric = 0.0;
			break;
		}
		return numeric;
	}
}
